package com.mrzhou.mybatis.support;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.CaseFormat;
import com.mrzhou.core.tool.utils.BeanUtil;
import com.mrzhou.core.tool.utils.StringUtil;

import java.util.Collection;
import java.util.Map;
import java.util.Optional;

/**
 * 一些mybatisPLUS的方法
 * @param
 */
public class Condition {

    public static <T> LambdaQueryWrapper<T> getQueryWrapper(Object query, Class<T> clazz) {
        return getQueryWrapper(BeanUtil.beanToMap(query), clazz).lambda();
    }

    /**
     * 将对象转换为mybatis-plus的查询对象
     * @param query
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> QueryWrapper<T> getQueryWrapper(Map<String, Object> query, Class<T> clazz) {
        query.remove("current");
        query.remove("size");
        query.remove("desc");
        query.remove("page");
        query.remove("asc");
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        Optional.of(query).ifPresent(param -> {
            param.forEach((key, value) -> {
                if(StringUtil.isAllBlank(new String[]{key, StringUtil.toStr(value)})) {
                    if(key.endsWith("_eq")) {
                        wrapper.eq(getColumn(key, "_eq"), value);
                    } else if (key.endsWith("_like")) {
                        wrapper.like(getColumn(key, "_like"), value);
                    } else if(key.endsWith("_like_left")) {
                        wrapper.likeLeft(getColumn(key, "_like_left"), value);
                    } else if(key.endsWith("_like_right")) {
                        wrapper.likeRight(getColumn(key, "_like_right"), value);
                    } else if(key.endsWith("_in")) {
                        // 为集合类型时强转
                        if (value instanceof Collection) {
                            wrapper.in(getColumn(key, "_in"), (Collection<?>) value);
                        } else {
                            wrapper.in(getColumn(key, "_in"), value);
                        }
                    } else {
                        wrapper.eq(getColumn(key, ""), value);
                    }
                }
            });
        });
        return wrapper;
    }

    private static String getColumn(String column, String keyword) {
        String str = column.trim().replaceAll(keyword, "");
        return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, str);
    }

}
